package com.example.backend.service;

import com.example.backend.domain.entity.*;
import com.example.backend.domain.enums.TicketPriority;
import com.example.backend.domain.enums.TicketStatus;
import com.example.backend.dto.StatisticsReportDto;
import com.example.backend.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统计报表服务
 * 提供实时统计、团队绩效、SLA统计、趋势图表等功能
 */
@Service
@Transactional
public class StatisticsReportService {

    private static final Logger log = LoggerFactory.getLogger(StatisticsReportService.class);

    @Autowired
    private TicketRepository ticketRepository;

    @Autowired
    private UserRepository userRepository;


    @Autowired
    private TicketSLARepository slaRepository;



    /**
     * 获取实时统计仪表盘
     */
    public StatisticsReportDto.DashboardStats getDashboardStats() {
        try {
            StatisticsReportDto.DashboardStats stats = new StatisticsReportDto.DashboardStats();
            
            // 基础统计
            stats.setTotalTickets(ticketRepository.count());
            stats.setOpenTickets(ticketRepository.countByStatus(TicketStatus.OPEN));
            stats.setInProgressTickets(ticketRepository.countByStatus(TicketStatus.IN_PROGRESS));
            stats.setResolvedTickets(ticketRepository.countByStatus(TicketStatus.RESOLVED));
            stats.setClosedTickets(ticketRepository.countByStatus(TicketStatus.CLOSED));
            
            // 时间范围统计
            Instant today = Instant.now().truncatedTo(ChronoUnit.DAYS);
            Instant weekAgo = Instant.now().minus(7, ChronoUnit.DAYS);
            Instant monthAgo = Instant.now().minus(30, ChronoUnit.DAYS);
            
            stats.setTodayTickets(ticketRepository.countByCreatedAtAfter(today));
            stats.setWeekTickets(ticketRepository.countByCreatedAtAfter(weekAgo));
            stats.setMonthTickets(ticketRepository.countByCreatedAtAfter(monthAgo));
            
            // 超时工单统计
            stats.setOverdueTickets(countOverdueTickets());
            
            // 平均解决时间
            stats.setAvgResolutionTimeHours(calculateAverageResolutionTime());
            
            // 平均满意度
            stats.setAvgSatisfactionScore(calculateAverageSatisfactionScore());
            
            // 分布统计
            stats.setPriorityDistribution(buildPriorityDistribution());
            stats.setStatusDistribution(buildStatusDistribution());
            stats.setSourceDistribution(buildSourceDistribution());
            
            // 顶级表现者 - 使用try-catch防止错误
            try {
                stats.setTopPerformers(getTopPerformers());
            } catch (Exception e) {
                stats.setTopPerformers(new ArrayList<>());
            }
            
            // 最近活动 - 使用try-catch防止错误
            try {
                stats.setRecentActivities(getRecentActivities());
            } catch (Exception e) {
                stats.setRecentActivities(new ArrayList<>());
            }
            
            return stats;
        } catch (Exception e) {
            log.error("获取仪表盘统计失败", e);
            // 如果发生异常，返回一个默认的空统计数据而不是抛出异常
            StatisticsReportDto.DashboardStats stats = new StatisticsReportDto.DashboardStats();
            stats.setTotalTickets(0L);
            stats.setOpenTickets(0L);
            stats.setInProgressTickets(0L);
            stats.setResolvedTickets(0L);
            stats.setClosedTickets(0L);
            stats.setTodayTickets(0L);
            stats.setWeekTickets(0L);
            stats.setMonthTickets(0L);
            stats.setOverdueTickets(0L);
            stats.setAvgResolutionTimeHours(0.0);
            stats.setAvgSatisfactionScore(0.0);
            stats.setPriorityDistribution(new HashMap<>());
            stats.setStatusDistribution(new HashMap<>());
            stats.setSourceDistribution(new HashMap<>());
            stats.setTopPerformers(new ArrayList<>());
            stats.setRecentActivities(new ArrayList<>());
            return stats;
        }
    }

    /**
     * 获取团队绩效报表
     */
    public StatisticsReportDto.TeamPerformanceReport getTeamPerformanceReport() {
        StatisticsReportDto.TeamPerformanceReport report = new StatisticsReportDto.TeamPerformanceReport();
        
        // 获取团队成员绩效
        List<User> teamMembers = new ArrayList<>();
        
        // 获取客服人员
        Page<User> agents = userRepository.findByRoleAndStatus(
            com.example.backend.domain.enums.Role.AGENT, 
            com.example.backend.domain.enums.UserStatus.ACTIVE,
            org.springframework.data.domain.Pageable.unpaged()
        );
        teamMembers.addAll(agents.getContent());
        
        // 获取管理员
        Page<User> admins = userRepository.findByRoleAndStatus(
            com.example.backend.domain.enums.Role.ADMIN, 
            com.example.backend.domain.enums.UserStatus.ACTIVE,
            org.springframework.data.domain.Pageable.unpaged()
        );
        teamMembers.addAll(admins.getContent());
        
        List<StatisticsReportDto.TeamMemberPerformance> memberPerformances = teamMembers.stream()
            .map(this::buildTeamMemberPerformance)
            .collect(Collectors.toList());
        
        report.setTeamMembers(memberPerformances);
        
        // 团队整体统计
        report.setOverallStats(buildTeamOverallStats(memberPerformances));
        
        // 绩效指标
        report.setMetrics(buildPerformanceMetrics());
        
        // 绩效趋势
        report.setTrends(buildPerformanceTrends());
        
        return report;
    }

    /**
     * 获取SLA统计报表
     */
    public StatisticsReportDto.SLAStatisticsReport getSLAStatisticsReport() {
        StatisticsReportDto.SLAStatisticsReport report = new StatisticsReportDto.SLAStatisticsReport();
        
        // 整体SLA达成率
        report.setOverallSLAAchievementRate(calculateOverallSLAAchievementRate());
        report.setResponseSLAAchievementRate(calculateResponseSLAAchievementRate());
        report.setResolutionSLAAchievementRate(calculateResolutionSLAAchievementRate());
        
        // 按优先级SLA统计
        report.setSlaByPriority(buildSLAByPriority());
        
        // 按分类SLA统计
        report.setSlaByCategory(buildSLAByCategory());
        
        // 按团队SLA统计
        report.setSlaByTeam(buildSLAByTeam());
        
        // SLA违规记录
        report.setSlaViolations(getSLAViolations());
        
        // SLA改进建议
        report.setSlaImprovements(getSLAImprovements());
        
        return report;
    }

    /**
     * 获取趋势图表数据
     */
    public StatisticsReportDto.TrendChartData getTrendChartData() {
        try {
            StatisticsReportDto.TrendChartData chartData = new StatisticsReportDto.TrendChartData();
            
            // 工单趋势
            try {
                chartData.setTicketTrend(buildTicketTrend());
            } catch (Exception e) {
                log.warn("构建工单趋势数据失败", e);
                chartData.setTicketTrend(new ArrayList<>());
            }
            
            // 解决趋势
            try {
                chartData.setResolutionTrend(buildResolutionTrend());
            } catch (Exception e) {
                log.warn("构建解决趋势数据失败", e);
                chartData.setResolutionTrend(new ArrayList<>());
            }
            
            // 满意度趋势
            try {
                chartData.setSatisfactionTrend(buildSatisfactionTrend());
            } catch (Exception e) {
                log.warn("构建满意度趋势数据失败", e);
                chartData.setSatisfactionTrend(new ArrayList<>());
            }
            
            // SLA趋势
            try {
                chartData.setSlaTrend(buildSLATrend());
            } catch (Exception e) {
                log.warn("构建SLA趋势数据失败", e);
                chartData.setSlaTrend(new ArrayList<>());
            }
            
            // 优先级趋势
            try {
                chartData.setPriorityTrend(buildPriorityTrend());
            } catch (Exception e) {
                log.warn("构建优先级趋势数据失败", e);
                chartData.setPriorityTrend(new ArrayList<>());
            }
            
            // 分类趋势
            try {
                chartData.setCategoryTrend(buildCategoryTrend());
            } catch (Exception e) {
                log.warn("构建分类趋势数据失败", e);
                chartData.setCategoryTrend(new ArrayList<>());
            }
            
            return chartData;
        } catch (Exception e) {
            log.error("获取趋势图表数据失败", e);
            StatisticsReportDto.TrendChartData chartData = new StatisticsReportDto.TrendChartData();
            chartData.setTicketTrend(new ArrayList<>());
            chartData.setResolutionTrend(new ArrayList<>());
            chartData.setSatisfactionTrend(new ArrayList<>());
            chartData.setSlaTrend(new ArrayList<>());
            chartData.setPriorityTrend(new ArrayList<>());
            chartData.setCategoryTrend(new ArrayList<>());
            return chartData;
        }
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 计算超时工单数量
     */
    private Long countOverdueTickets() {
        long openOverdue = ticketRepository.countByStatus(TicketStatus.OPEN);
        long inProgressOverdue = ticketRepository.countByStatus(TicketStatus.IN_PROGRESS);
        // 这里简化处理，实际应该查询有dueDate且已过期的工单
        return openOverdue + inProgressOverdue;
    }

    /**
     * 计算平均解决时间
     */
    private Double calculateAverageResolutionTime() {
        Double result = ticketRepository.getAverageResolutionTimeInHours();
        return result != null ? result : 0.0;
    }

    /**
     * 计算平均满意度
     */
    private Double calculateAverageSatisfactionScore() {
        // 简化处理，返回默认值
        // 实际应该查询有满意度评分的工单
        return 4.2; // 默认满意度分数
    }

    /**
     * 构建优先级分布
     */
    private Map<String, Long> buildPriorityDistribution() {
        Map<String, Long> distribution = new HashMap<>();
        for (TicketPriority priority : TicketPriority.values()) {
            distribution.put(priority.name(), ticketRepository.countByPriority(priority));
        }
        return distribution;
    }

    /**
     * 构建状态分布
     */
    private Map<String, Long> buildStatusDistribution() {
        Map<String, Long> distribution = new HashMap<>();
        for (TicketStatus status : TicketStatus.values()) {
            distribution.put(status.name(), ticketRepository.countByStatus(status));
        }
        return distribution;
    }

    /**
     * 构建来源分布
     */
    private Map<String, Long> buildSourceDistribution() {
        Map<String, Long> distribution = new HashMap<>();
        for (com.example.backend.domain.enums.TicketSource source : 
             com.example.backend.domain.enums.TicketSource.values()) {
            distribution.put(source.name(), ticketRepository.countBySource(source));
        }
        return distribution;
    }

    /**
     * 获取顶级表现者
     */
    private List<StatisticsReportDto.TopPerformer> getTopPerformers() {
        Page<User> agentPage = userRepository.findByRoleAndStatus(
            com.example.backend.domain.enums.Role.AGENT, 
            com.example.backend.domain.enums.UserStatus.ACTIVE,
            org.springframework.data.domain.Pageable.unpaged()
        );
        List<User> agents = agentPage.getContent();
        
        return agents.stream()
            .map(this::buildTopPerformer)
            .filter(Objects::nonNull)
            .sorted((a, b) -> Double.compare(b.getSlaAchievementRate(), a.getSlaAchievementRate()))
            .limit(5)
            .collect(Collectors.toList());
    }

    /**
     * 构建顶级表现者
     */
    private StatisticsReportDto.TopPerformer buildTopPerformer(User user) {
        List<Object[]> assigneeStats = ticketRepository.getTicketStatsByAssignee(user.getId());
        if (assigneeStats.isEmpty()) {
            return null;
        }
        
        StatisticsReportDto.TopPerformer performer = new StatisticsReportDto.TopPerformer();
        performer.setUserId(user.getId());
        performer.setUserName(user.getFullName());
        performer.setUserRole(user.getRole().name());
        
        // 计算统计数据
        long resolvedTickets = 0;
        for (Object[] stat : assigneeStats) {
            TicketStatus status = (TicketStatus) stat[0];
            Long count = (Long) stat[1];
            if (status == TicketStatus.RESOLVED || status == TicketStatus.CLOSED) {
                resolvedTickets += count;
            }
        }
        
        performer.setTicketsResolved(resolvedTickets);
        performer.setAvgResolutionTime(calculateAverageResolutionTime());
        performer.setAvgSatisfactionScore(calculateAverageSatisfactionScore());
        performer.setSlaAchievementRate(calculateUserSLAAchievementRate(user.getId()));
        
        return performer;
    }

    /**
     * 获取最近活动
     */
    private List<StatisticsReportDto.RecentActivity> getRecentActivities() {
        List<StatisticsReportDto.RecentActivity> activities = new ArrayList<>();
        
        // 获取最近的工单更新
        List<Ticket> recentTickets = ticketRepository.findTop10ByOrderByCreatedAtDesc();
        for (Ticket ticket : recentTickets) {
            StatisticsReportDto.RecentActivity activity = new StatisticsReportDto.RecentActivity();
            activity.setActivityType("TICKET_UPDATE");
            activity.setDescription("工单状态更新为 " + ticket.getStatus().name());
            activity.setUserName(ticket.getAssignedTo() != null ? ticket.getAssignedTo().getFullName() : "系统");
            activity.setTimestamp(ticket.getUpdatedAt());
            activity.setTicketId(ticket.getId());
            activity.setTicketNumber(ticket.getTicketNumber());
            activities.add(activity);
        }
        
        return activities.stream()
            .sorted((a, b) -> b.getTimestamp().compareTo(a.getTimestamp()))
            .limit(10)
            .collect(Collectors.toList());
    }

    /**
     * 构建团队成员绩效
     */
    private StatisticsReportDto.TeamMemberPerformance buildTeamMemberPerformance(User user) {
        StatisticsReportDto.TeamMemberPerformance performance = new StatisticsReportDto.TeamMemberPerformance();
        
        performance.setUserId(user.getId());
        performance.setUserName(user.getFullName());
        performance.setUserRole(user.getRole().name());
        performance.setDepartment(user.getDepartment());
        
        // 获取工单统计
        List<Object[]> assigneeStats = ticketRepository.getTicketStatsByAssignee(user.getId());
        long totalTickets = 0;
        long resolvedTickets = 0;
        long overdueTickets = 0;
        
        Map<String, Long> ticketsByStatus = new HashMap<>();
        for (Object[] stat : assigneeStats) {
            TicketStatus status = (TicketStatus) stat[0];
            Long count = (Long) stat[1];
            totalTickets += count;
            ticketsByStatus.put(status.name(), count);
            
            if (status == TicketStatus.RESOLVED || status == TicketStatus.CLOSED) {
                resolvedTickets += count;
            }
        }
        
        performance.setTotalTickets(totalTickets);
        performance.setResolvedTickets(resolvedTickets);
        performance.setOverdueTickets(overdueTickets);
        performance.setAvgResolutionTimeHours(calculateAverageResolutionTime());
        performance.setAvgSatisfactionScore(calculateAverageSatisfactionScore());
        performance.setSlaAchievementRate(calculateUserSLAAchievementRate(user.getId()));
        performance.setTicketsByStatus(ticketsByStatus);
        
        return performance;
    }

    /**
     * 构建团队整体统计
     */
    private StatisticsReportDto.TeamOverallStats buildTeamOverallStats(
            List<StatisticsReportDto.TeamMemberPerformance> memberPerformances) {
        
        StatisticsReportDto.TeamOverallStats stats = new StatisticsReportDto.TeamOverallStats();
        
        stats.setTotalTeamMembers((long) memberPerformances.size());
        stats.setActiveTeamMembers((long) memberPerformances.stream()
            .filter(m -> m.getTotalTickets() > 0)
            .count());
        
        stats.setTotalTicketsHandled(memberPerformances.stream()
            .mapToLong(StatisticsReportDto.TeamMemberPerformance::getTotalTickets)
            .sum());
        
        stats.setTeamAvgResolutionTimeHours(memberPerformances.stream()
            .mapToDouble(StatisticsReportDto.TeamMemberPerformance::getAvgResolutionTimeHours)
            .average()
            .orElse(0.0));
        
        stats.setTeamAvgSatisfactionScore(memberPerformances.stream()
            .mapToDouble(StatisticsReportDto.TeamMemberPerformance::getAvgSatisfactionScore)
            .average()
            .orElse(0.0));
        
        stats.setTeamSLAAchievementRate(memberPerformances.stream()
            .mapToDouble(StatisticsReportDto.TeamMemberPerformance::getSlaAchievementRate)
            .average()
            .orElse(0.0));
        
        return stats;
    }

    /**
     * 构建绩效指标
     */
    private List<StatisticsReportDto.PerformanceMetric> buildPerformanceMetrics() {
        List<StatisticsReportDto.PerformanceMetric> metrics = new ArrayList<>();
        
        // 工单解决率
        StatisticsReportDto.PerformanceMetric resolutionRate = new StatisticsReportDto.PerformanceMetric();
        resolutionRate.setMetricName("工单解决率");
        resolutionRate.setMetricDescription("已解决工单占总工单的比例");
        resolutionRate.setCurrentValue(calculateResolutionRate());
        resolutionRate.setTargetValue(85.0);
        resolutionRate.setUnit("%");
        metrics.add(resolutionRate);
        
        // 平均解决时间
        StatisticsReportDto.PerformanceMetric avgResolutionTime = new StatisticsReportDto.PerformanceMetric();
        avgResolutionTime.setMetricName("平均解决时间");
        avgResolutionTime.setMetricDescription("工单从创建到解决的平均时间");
        avgResolutionTime.setCurrentValue(calculateAverageResolutionTime());
        avgResolutionTime.setTargetValue(24.0);
        avgResolutionTime.setUnit("小时");
        metrics.add(avgResolutionTime);
        
        // 客户满意度
        StatisticsReportDto.PerformanceMetric satisfaction = new StatisticsReportDto.PerformanceMetric();
        satisfaction.setMetricName("客户满意度");
        satisfaction.setMetricDescription("客户对工单处理的满意度评分");
        satisfaction.setCurrentValue(calculateAverageSatisfactionScore());
        satisfaction.setTargetValue(4.5);
        satisfaction.setUnit("分");
        metrics.add(satisfaction);
        
        return metrics;
    }

    /**
     * 构建绩效趋势
     */
    private List<StatisticsReportDto.PerformanceTrend> buildPerformanceTrends() {
        List<StatisticsReportDto.PerformanceTrend> trends = new ArrayList<>();
        
        // 工单数量趋势
        StatisticsReportDto.PerformanceTrend ticketTrend = new StatisticsReportDto.PerformanceTrend();
        ticketTrend.setMetricName("工单数量趋势");
        ticketTrend.setDataPoints(buildTicketTrend());
        ticketTrend.setTrendDirection("UP");
        trends.add(ticketTrend);
        
        return trends;
    }

    /**
     * 计算整体SLA达成率
     */
    private Double calculateOverallSLAAchievementRate() {
        long totalSLARecords = slaRepository.count();
        if (totalSLARecords == 0) {
            return 0.0;
        }
        
        long violatedRecords = slaRepository.countViolatedResponseSLA(Instant.now()) + 
                              slaRepository.countViolatedResolutionSLA(Instant.now());
        
        return ((double) (totalSLARecords - violatedRecords) / totalSLARecords) * 100;
    }

    /**
     * 计算响应SLA达成率
     */
    private Double calculateResponseSLAAchievementRate() {
        long totalRecords = slaRepository.count();
        if (totalRecords == 0) {
            return 0.0;
        }
        
        long violatedRecords = slaRepository.countViolatedResponseSLA(Instant.now());
        return ((double) (totalRecords - violatedRecords) / totalRecords) * 100;
    }

    /**
     * 计算解决SLA达成率
     */
    private Double calculateResolutionSLAAchievementRate() {
        long totalRecords = slaRepository.count();
        if (totalRecords == 0) {
            return 0.0;
        }
        
        long violatedRecords = slaRepository.countViolatedResolutionSLA(Instant.now());
        return ((double) (totalRecords - violatedRecords) / totalRecords) * 100;
    }

    /**
     * 构建按优先级SLA统计
     */
    private Map<String, Double> buildSLAByPriority() {
        Map<String, Double> slaByPriority = new HashMap<>();
        for (TicketPriority priority : TicketPriority.values()) {
            slaByPriority.put(priority.name(), calculatePrioritySLAAchievementRate(priority));
        }
        return slaByPriority;
    }

    /**
     * 构建按分类SLA统计
     */
    private Map<String, Double> buildSLAByCategory() {
        // 这里需要根据实际分类数据实现
        return new HashMap<>();
    }

    /**
     * 构建按团队SLA统计
     */
    private Map<String, Double> buildSLAByTeam() {
        Map<String, Double> slaByTeam = new HashMap<>();
        
        Page<User> agentPage = userRepository.findByRoleAndStatus(
            com.example.backend.domain.enums.Role.AGENT, 
            com.example.backend.domain.enums.UserStatus.ACTIVE,
            org.springframework.data.domain.Pageable.unpaged()
        );
        List<User> agents = agentPage.getContent();
        for (User agent : agents) {
            slaByTeam.put(agent.getFullName(), calculateUserSLAAchievementRate(agent.getId()));
        }
        
        return slaByTeam;
    }

    /**
     * 获取SLA违规记录
     */
    private List<StatisticsReportDto.SLAViolation> getSLAViolations() {
        // 这里需要根据实际SLA违规数据实现
        return new ArrayList<>();
    }

    /**
     * 获取SLA改进建议
     */
    private List<StatisticsReportDto.SLAImprovement> getSLAImprovements() {
        List<StatisticsReportDto.SLAImprovement> improvements = new ArrayList<>();
        
        StatisticsReportDto.SLAImprovement improvement = new StatisticsReportDto.SLAImprovement();
        improvement.setImprovementArea("响应时间");
        improvement.setSuggestion("优化工单分配流程，减少响应时间");
        improvement.setPriority("HIGH");
        improvement.setExpectedImprovement(15.0);
        improvement.setImplementationEffort("中等");
        improvements.add(improvement);
        
        return improvements;
    }

    /**
     * 构建工单趋势
     */
    private List<StatisticsReportDto.ChartDataPoint> buildTicketTrend() {
        List<StatisticsReportDto.ChartDataPoint> trend = new ArrayList<>();
        
        try {
            // 获取最近30天的数据
            Instant endDate = Instant.now();
            Instant startDate = endDate.minus(30, ChronoUnit.DAYS);
            
            List<Object[]> trendData = ticketRepository.getTicketTrendData(startDate, endDate);
            if (trendData != null) {
                for (Object[] data : trendData) {
                    if (data != null && data.length >= 2 && data[0] != null && data[1] != null) {
                        StatisticsReportDto.ChartDataPoint point = new StatisticsReportDto.ChartDataPoint();
                        point.setLabel(data[0].toString());
                        if (data[1] instanceof Number) {
                            point.setValue(((Number) data[1]).doubleValue());
                        } else {
                            point.setValue(0.0);
                        }
                        point.setTimestamp(Instant.now());
                        trend.add(point);
                    }
                }
            }
        } catch (Exception e) {
            log.error("构建工单趋势数据时发生错误", e);
        }
        
        // 如果没有数据，返回空列表而不是null
        return trend;
    }

    /**
     * 构建解决趋势
     */
    private List<StatisticsReportDto.ChartDataPoint> buildResolutionTrend() {
        // 类似工单趋势的实现
        return new ArrayList<>();
    }

    /**
     * 构建满意度趋势
     */
    private List<StatisticsReportDto.ChartDataPoint> buildSatisfactionTrend() {
        // 类似工单趋势的实现
        return new ArrayList<>();
    }

    /**
     * 构建SLA趋势
     */
    private List<StatisticsReportDto.ChartDataPoint> buildSLATrend() {
        // 类似工单趋势的实现
        return new ArrayList<>();
    }

    /**
     * 构建优先级趋势
     */
    private List<StatisticsReportDto.ChartDataPoint> buildPriorityTrend() {
        // 类似工单趋势的实现
        return new ArrayList<>();
    }

    /**
     * 构建分类趋势
     */
    private List<StatisticsReportDto.ChartDataPoint> buildCategoryTrend() {
        // 类似工单趋势的实现
        return new ArrayList<>();
    }

    // ==================== 辅助计算方法 ====================

    private Double calculateResolutionRate() {
        long totalTickets = ticketRepository.count();
        if (totalTickets == 0) {
            return 0.0;
        }
        
        long resolvedTickets = ticketRepository.countByStatus(TicketStatus.RESOLVED) + 
                              ticketRepository.countByStatus(TicketStatus.CLOSED);
        
        return ((double) resolvedTickets / totalTickets) * 100;
    }

    private Double calculatePrioritySLAAchievementRate(TicketPriority priority) {
        // 根据优先级计算SLA达成率
        return 85.0; // 示例值
    }

    private Double calculateUserSLAAchievementRate(Long userId) {
        // 根据用户计算SLA达成率
        return 90.0; // 示例值
    }
}
